#include "FileDownloaderProcess.h"

FileDownloaderProcess::FileDownloaderProcess(LogFile* logFile) : Process(logFile) {
}

void FileDownloaderProcess::setDownloadFilePath(string downloadFilePath) {
	this->downloadFilePath = downloadFilePath;
}

void FileDownloaderProcess::setDownloadFifoPath(string downloadFifoPath) {
	this->downloadFifoPath = downloadFifoPath;
}

int FileDownloaderProcess::doWork() {
	this->logFile->log("[" + this->getProcessName() + "] Creando fifo de descarga: " + this->downloadFifoPath);
	FileTransferFifo fifo(this->downloadFifoPath);

	this->logFile->log("[" + this->getProcessName() + "] Creando nuevo archivo en carpeta de descargas: " + this->downloadFilePath);
	DownloadedFile file(this->downloadFilePath);
	file.getWriteLock();

	this->logFile->log("[" + this->getProcessName() + "] Descargando archivo.");
	char chunk[TRANSFERFILEBUFFERSIZE];
	int readBytes = fifo.readData(chunk, TRANSFERFILEBUFFERSIZE);
	while(readBytes > 0) {
		file.writeData(chunk, readBytes);
		readBytes = fifo.readData(chunk, TRANSFERFILEBUFFERSIZE);
	}

	this->logFile->log("[" + this->getProcessName() + "] Descarga finalizada. Lanzando señal para notificar.");
	raise(SIGUSR2);

	// Unlink del fifo.
	fifo.destroy();

	file.unlock();

	return 0;
}

string FileDownloaderProcess::getProcessName() {
	return string("FileDownloader");
}

FileDownloaderProcess::~FileDownloaderProcess() {
}

